package spring6_learn.com.powernode.client;

import spring6_learn.com.powernode.annotion.Component;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class AnnotationScan {
    public static void main(String[] args) throws NoSuchMethodException {
        Map<String,Object> Beanmap = new HashMap<>();
        String packageName="spring6_learn.com.powernode.bean";
        //获取包名对应的路径
        String path = packageName.replaceAll("\\.", "/");
       // System.out.println("path = " + path);//path = spring6_learn/com/powernode/bean
        //获取绝对路径
        URL url = ClassLoader.getSystemClassLoader().getResource(path);
       // System.out.println("url = " + url);//url = file:/D:/GEL/Spring6/Spring6_learn/springAnnotation/target/classes/spring6_learn/com/powernode/bean
        String urlPath = url.getPath();
        //System.out.println("urlPath = " + urlPath);//urlPath = /D:/GEL/Spring6/Spring6_learn/springAnnotation/target/classes/spring6_learn/com/powernode/bean
        File file = new File(urlPath);//获取包名对应的目录
        //System.out.println("file = " + file);
        File[] files = file.listFiles();//获取包名对应的目录下的所有文件
        for(File f:files){
            String name = f.getName();
            //System.out.println("name = " + name);//name = Client.class
            String ClassName = name.split("\\.")[0];
            //System.out.println("ClassName = " + ClassName);//name = Client
            //组合文件的包路径
            String className = packageName + "." + ClassName;
            //通过反射获取类，分析注解
            try {
                Class<?> aClass = Class.forName(className);
                if(aClass.isAnnotationPresent(Component.class)){
                    //获取注解
                    Component annotation = aClass.getAnnotation(Component.class);
                    String id=annotation.value();
                    System.out.println("annotation.value() = " + id);
                    //有这个注解的创建对象
                    Constructor<?> declaredConstructor = aClass.getDeclaredConstructor();
                    Object obj = declaredConstructor.newInstance();
                    Beanmap.put(id,obj);

                }

            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
                     InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(Beanmap.toString());

    }
}
